package com.sgb.kjwl.view.ui.activity.enterprise;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPublishServiceDetailBinding;
import com.sgb.kjwl.di.enterprise.DaggerEnterpriseComponent;
import com.sgb.kjwl.di.enterprise.EnterpriseModule;
import com.sgb.kjwl.model.entity.enterprise.EpQuoteEntity;
import com.sgb.kjwl.model.entity.enterprise.TransactionCasesEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.sgb.kjwl.utils.DisplayUtil;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.adapter.enterprise.DealedCasesDetailAdapter;
import com.sgb.kjwl.view.ui.adapter.enterprise.ServiceNodeAdpater;
import com.sgb.link.view.widget.ExpandedTextView;
import com.sgb.kjwl.viewmodel.enterprise.PublishServiceDetailActivityModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.MToast;
import com.zhy.view.flowlayout.TagAdapter;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * Time:2021/4/16
 * Author:黄淋
 * Description:发布的服务详情
 */
public class PublishServiceDetailActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    ActivityPublishServiceDetailBinding mBinding;
    private static final int MSG_LOAD_DATA = 0x0001;

    @Inject
    PublishServiceDetailActivityModel mModel;
    long id;
    private DealedCasesDetailAdapter mAdapter;
    private ServiceNodeAdpater serviceNodeAdpater;
    EpQuoteEntity mEntity;
    ArrayList<BaseAreaEntity> mCityList;
    private String serviceProJson;


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseComponent.builder()
                .appComponent(appComponent)
                .enterpriseModule(new EnterpriseModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_publish_service_detail);
        mBinding.tvEnable.setOnClickListener(this);
        mBinding.tvEdit.setOnClickListener(this);
        mBinding.tvDelete.setOnClickListener(this);
        mBinding.tvShowMore.setOnClickListener(this);
        mBinding.tvOperateDown.setOnClickListener(this);
        mBinding.itvServiceCity.setOnClickListener(this);
        mBinding.itvServiceItem.setOnWholeItemClickListener(this);
        mBinding.itvServiceLiuCheng.setOnWholeItemClickListener(this);
        mBinding.cityList.setClickable(false);
        initAdapter();
        onObserve();
    }

    private void initAdapter() {
        mAdapter = new DealedCasesDetailAdapter(this, null);
        mBinding.rvCases.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rvCases.setAdapter(mAdapter);

        serviceNodeAdpater = new ServiceNodeAdpater(this);
        mBinding.rvServiceNode.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rvServiceNode.setAdapter(serviceNodeAdpater);
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.shape_list_divide_05));
        mBinding.rvServiceNode.addItemDecoration(divider);
    }

    @Override
    protected void init() {
        id = getIntent().getLongExtra("id", 0);
//        mModel.getServiceHallDetail(this, id);
//        mModel.getTransactionList(this, String.valueOf(id));
        mModel.ldServiceDetail.observe(this, this::setDetail);
        mModel.ldCaseList.observe(this, this::showList);
        mModel.ldServiceStatus.observe(this, a -> mModel.getServiceHallDetail(this, id));
        mModel.ldServiceDelete.observe(this, a -> {
            if (a.equals("true")) {
                ActivityJump.jumpToActivity(this, PublishServiceListActivity.class);
            }
        });
        mModel.getServiceNodeList(id + "");
        mBinding.itvServiceLiuCheng.setLabelTextBold(true);
    }


    @Override
    protected void onResume() {
        super.onResume();
        mModel.getServiceHallDetail(this, id);
        mModel.getTransactionList(this, String.valueOf(id));
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_enable://上架
                if (mEntity != null && mEntity.getStatus() != null) {
                    DialogHelper.showDialog(getActivity(), "温馨提示", "是否确认上架？", "确定", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            mModel.getPublishServiceEnable(PublishServiceDetailActivity.this, id, "1");
                        }
                    });
                }
                break;
            case R.id.tv_operate_down://下架
                if (mEntity != null && mEntity.getStatus() != null) {
                    DialogHelper.showDialog(getActivity(), "温馨提示", "是否确认下架？", "确定", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            mModel.getPublishServiceEnable(PublishServiceDetailActivity.this, id, "-1");
                        }
                    });
                }
                break;
            case R.id.tv_edit://编辑
                ActivityJump.jumpToActivity(this, PublishServiceActivity.class, Pair.create(RouterKey.DATA, mEntity));
                break;
            case R.id.tv_delete://删除
                DialogHelper.showDialog(getActivity(), "温馨提示", "是否确认删除？", "确定", new DialogFunction() {
                    @Override
                    public void normalRoundDialog() {
                        mModel.deleteService(PublishServiceDetailActivity.this, id);
                    }
                });
                break;
            case R.id.tv_show_more://更多
                ActivityJump.jumpToActivity(this, PublishedDealedCasesActivity.class, Pair.create("id", id));
                break;
            case R.id.itv_service_city://更多
                if (mCityList != null && mCityList.size() > 0)
                    PublishServiceCityShowActivity.start(this, mCityList);
                break;
        }
    }


    private void onObserve() {
        mModel.serviceNodeList.observe(this, serviceNodeListEntities -> {
            if (null != serviceNodeListEntities && serviceNodeListEntities.size() > 0) {
                mBinding.rvServiceNode.setVisibility(View.VISIBLE);
                mBinding.emptyViewNode.setVisibility(View.GONE);
                serviceNodeAdpater.setDatas(serviceNodeListEntities);
                mBinding.itvServiceLiuCheng.setColor(getResources().getColor(R.color.new_blue));
                mBinding.itvServiceLiuCheng.setArrowRightImage(R.mipmap.right_arrow_blue);
                mBinding.itvServiceLiuCheng.setDeliverLineVG(true);
            } else {
                serviceNodeAdpater.setDatasMayNull(null);
                mBinding.emptyViewNode.setVisibility(View.VISIBLE);
                mBinding.itvServiceLiuCheng.setContent("");
                mBinding.itvServiceLiuCheng.setArrowVisible(false);
                mBinding.itvServiceLiuCheng.setDeliverLineVG(false);
            }
        });

        mModel.toast.observe(this, s -> {
            MToast.showToast(this, s);
        });
        mModel.ShowLoading.observe(this, integer -> {
            switch (integer) {
                case 1:
                    com.swgk.core.dialog.DialogHelper.showProgressDialog(getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    break;
                case 2:
                    com.swgk.core.dialog.DialogHelper.dismissProgressDialog();
                    break;
            }
        });
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void setDetail(EpQuoteEntity entity) {
        if (entity != null) {
            mEntity = entity;
            mBinding.setViewModel(entity);
            mCityList = jsonToArrayList(entity.getServiceCitys(), BaseAreaEntity.class);
            mBinding.tvMore.setVisibility(mCityList.size() > 2 ? View.VISIBLE : View.GONE);

            final LayoutInflater mInflater = LayoutInflater.from(PublishServiceDetailActivity.this);
            List<BaseAreaEntity> cityListShow = mCityList.size() > 1 ? mCityList.subList(0, 2) : mCityList;
            TagAdapter cityAdapter = new TagAdapter<BaseAreaEntity>(cityListShow) {
                @Override
                public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, BaseAreaEntity entity) {
                    LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_service_detail_part_city, mBinding.cityList, false);
                    TextView tv = layout.findViewById(R.id.tv_info);
                    tv.setText(entity.getName());
                    return layout;
                }
            };
            //是否是默认 服务项目
            if (TextUtils.isEmpty(entity.getProjectClassificationJson())) {
                //默认
                mBinding.itvServiceItem.setContent("默认服务项目");
                mBinding.itvServiceItem.setArrowVisible(false);
                mBinding.itvServicePrice.setVisibility(View.VISIBLE);
            } else {
                //自定义
                mBinding.itvServiceItem.setContent("查看更多");
                mBinding.itvServiceItem.setColor(getResources().getColor(R.color.new_blue));
                mBinding.itvServiceItem.setArrowRightImage(R.mipmap.right_arrow_blue);
                mBinding.itvServiceItem.setArrowVisible(true);
                mBinding.itvServicePrice.setVisibility(View.GONE);
                serviceProJson = entity.getOtherQualificationPrices();
            }
            mBinding.cityList.setAdapter(cityAdapter);
            if (entity.getStatus().equals("1")) {
                mBinding.llOperateUp.setVisibility(View.GONE);
                mBinding.tvOperateDown.setVisibility(View.VISIBLE);
            } else {
                mBinding.llOperateUp.setVisibility(View.VISIBLE);
                mBinding.tvOperateDown.setVisibility(View.GONE);
            }
            String subStr = "";
            if (entity.getFirstCategoryName() != null && !entity.getFirstCategoryName().equals("")) {
                subStr = entity.getFirstCategoryName();
                if (entity.getSecondCategoryName() != null && !entity.getSecondCategoryName().equals("")) {
                    String two = entity.getSecondCategoryName();
                    subStr = subStr + "-" + two;
                }
                if (entity.getItemName() != null && !entity.getItemName().equals("")) {
                    String three = entity.getItemName();
                    subStr = subStr + "-" + three;
                }
            }
            mBinding.tvPublishDetailServiceType.setText(subStr);
            mBinding.tvItem.setText(entity.getServiceDetails());

            String content = mEntity.getDescription();
            if (content != null && !content.equals("")) {
                WebSettings webSettings = mBinding.webDescription.getSettings();
                webSettings.setUseWideViewPort(true);
                webSettings.setLoadWithOverviewMode(true);
                webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
                mBinding.webDescription.setHorizontalScrollBarEnabled(false);
                mBinding.webDescription.setVerticalScrollBarEnabled(false);
                mBinding.webDescription.loadDataWithBaseURL(null, setWebViewContent(content), "text/html", "UTF-8", null);
                mBinding.webDescription.requestLayout();
                mBinding.webDescription.requestLayout();
                mBinding.webDescription.setVisibility(View.VISIBLE);
                mBinding.emptyView.setVisibility(View.GONE);
            } else {
                mBinding.webDescription.setVisibility(View.GONE);
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
            mHandler.sendEmptyMessageDelayed(MSG_LOAD_DATA, 100);
        }
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    try {
                        mBinding.nsvDetail.setVisibility(View.VISIBLE);
                        new ExpandedTextView().showTextPick(mBinding.tvItem, mBinding.noteOnOff);
                        if (mBinding.tvMore.getVisibility() == View.VISIBLE) {
                            mBinding.arrowRight.setVisibility(View.VISIBLE);
                            mBinding.itvServiceCity.setClickable(true);
                        } else {
                            mBinding.arrowRight.setVisibility(View.GONE);
                            mBinding.itvServiceCity.setClickable(false);
                        }
                        if (mCityList.size() > 1 &&
                                DisplayUtil.px2dip(PublishServiceDetailActivity.this, mBinding.cityList.getChildAt(0).getMeasuredWidth() + mBinding.cityList.getChildAt(1).getMeasuredWidth()) > 250) {
                            ArrayList<BaseAreaEntity> cityListShowEnd = new ArrayList<>();
                            cityListShowEnd.add(mCityList.get(0));
                            mBinding.tvMore.setVisibility(View.VISIBLE);
                            mBinding.arrowRight.setVisibility(View.VISIBLE);
                            mBinding.itvServiceCity.setClickable(true);
                            final LayoutInflater mInflater = LayoutInflater.from(PublishServiceDetailActivity.this);
                            TagAdapter cityAdapter2 = new TagAdapter<BaseAreaEntity>(cityListShowEnd) {
                                @Override
                                public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, BaseAreaEntity entity) {
                                    LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_service_detail_part_city, mBinding.cityList, false);
                                    TextView tv = layout.findViewById(R.id.tv_info);
                                    tv.setText(entity.getName());
                                    return layout;
                                }
                            };
                            mBinding.cityList.setAdapter(cityAdapter2);
                        }
                    } catch (Exception exc) {
                        exc.printStackTrace();
                    }
            }
        }
    };

    /**
     * 服务报价数据
     *
     * @param list
     */
    public void showList(List<TransactionCasesEntity> list) {
        if (null != list && list.size() > 0) {
            mBinding.tvKeyCases.setVisibility(View.VISIBLE);
            mBinding.rvCases.setVisibility(View.VISIBLE);
            mBinding.emptyViewCases.setVisibility(View.GONE);
            mBinding.tvShowMore.setVisibility(list.size() > 3 ? View.VISIBLE : View.GONE);
            if (list.size() > 3)
                list = list.subList(0, 3);
            mAdapter.setDatas(list);
        } else {
            mAdapter.setDatasMayNull(null);
            mBinding.emptyViewCases.setVisibility(View.VISIBLE);
            mBinding.rvCases.setVisibility(View.GONE);
            mBinding.tvKeyCases.setVisibility(View.VISIBLE);
            mBinding.tvShowMore.setVisibility(View.GONE);
        }
    }


    /**
     * @param json
     * @param clazz
     * @return
     */
    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<T> arrayList = new ArrayList<>();
        try {
            ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

            for (JsonObject jsonObject : jsonObjects) {
                arrayList.add(new Gson().fromJson(jsonObject, clazz));
            }
        } catch (Exception e) {

        }

        return arrayList;
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.itv_service_item:
                if (mBinding.itvServiceItem.getContent().equals("查看更多"))
                    ServiceProListActivity.startActivity(PublishServiceDetailActivity.this, id + "", serviceProJson, 0);
                break;
            case R.id.itv_service_liu_cheng:
//                if (mBinding.itvServiceItem.getContent().equals("查看更多"))
                ServiceProListActivity.startActivity(PublishServiceDetailActivity.this, id + "", serviceProJson, 1);
                break;
        }
    }

    /**
     * 适配image和table标签
     */
    private static String setWebViewContent(String content) {
        String head = "<style type=\"text/css\"> img {" +
                "width:100%;" +//限定图片宽度填充屏幕
                "height:auto;" +//限定图片高度自动
                "}" +
                "body {" +
                "margin-right:15px;" +//限定网页中的文字右边距为15px(可根据实际需要进行行管屏幕适配操作)
                "margin-left:30px;" +//限定网页中的文字左边距为15px(可根据实际需要进行行管屏幕适配操作)
                "margin-top:15px;" +//限定网页中的文字上边距为15px(可根据实际需要进行行管屏幕适配操作)
                "font-size:38px;" +//限定网页中文字的大小为40px,请务必根据各种屏幕分辨率进行适配更改
                "word-wrap:break-word;" +//允许自动换行(汉字网页应该不需要这一属性,这个用来强制英文单词换行,类似于word/wps中的西文换行)
                "}" +
                "</style>";
        return "<html><header>" + head + "</header>" + content + "</html>";
    }
}
